package system;

import Main.*;
import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

/**
 * Read message locale file specified in settings.ini
 * @author ZeM
 */
public class MessageOUTPUT {

    /**
     * Read Message from locale file
     * @param mes -name of message
     * @param path -path to locale file
     * @param message_parameters - message parameters
     * @return message string value
     */
    private String ReadMessage(String mes, File path, String[] message_parameters){

    String message = null;
        try {

            DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
            File locale=path;

            Document doc = docBuilder.parse(locale);
            // normalize text representation
            doc.getDocumentElement().normalize();

//reading  parameters

            NodeList listOfTasks = doc.getElementsByTagName("messages");
            int totalTasks = listOfTasks.getLength();
            for (int tc = 0; tc < totalTasks; tc++) {
                Node firstPersonNode = listOfTasks.item(tc);
                if (firstPersonNode.getNodeType() == Node.ELEMENT_NODE) {
                    Element firstPersonElement = (Element) firstPersonNode;
                    boolean flag = true; //mean that everithing is OK
                    //----description
                    NodeList nodelist = firstPersonElement.getElementsByTagName(mes);
                    int length = nodelist.getLength();
                    if (length > 0) {
                        Element nelement = (Element) nodelist.item(0);
                        NodeList textList = nelement.getChildNodes();
                        message = ((Node) textList.item(0)).getNodeValue().trim();



                        char[] tmp = message.toCharArray();
                        if (tmp[0] == '"') {
                            if (tmp[tmp.length - 1] == '"') {
                                message = "";
                                boolean parameterflag = false;
                                for (int i = 1; i < tmp.length - 1; i++) {
                                    if (!parameterflag) {
                                        if (tmp[i] == '$') {
                                            parameterflag = true;
                                        } else {
                                            message += tmp[i];
                                        }
                                    } else {
                                        parameterflag = false;
                                        message += message_parameters[Integer.parseInt("" + tmp[i])];
                                    }
                                }
                            }
                        }
                    }
                }
            }
        } catch (Exception er) {
        }
        return message;

    }

    /**
     * Read message from system locale file.
     * @param mes -name of message
     * @return message string value
     */
    public String Message(String mes, String[] param) {
        String message = null;
        try {

            
            File locale=new File("locale" + File.separatorChar + "locale." + Parameters.Language + ".xml");
            if(!locale.exists()){ //if locale file doesn't exists
                locale=new File("locale" + File.separatorChar + "locale.eng.xml");
                String m="ERROR: can't find locale for current system language - "+Parameters.Language;
                new MessageOUTPUT().OutputToCUI(m);
                new MessageOUTPUT().OutputToGUI(m);
            }

            message=ReadMessage(mes,locale,param);
        } catch (Exception er) {
        }
        return message;
    }



   /**
    * Read message from plugin locale file.
    * @param mes -name of message
    * @return message string value
    */
    private String PluginMessage(String mes,String[] param) {
        String message = null;
        try {

            
            File locale=new File(Parameters.PluginDirectory +File.separatorChar+ "locale." + Parameters.Language + ".xml");
            if(!locale.exists()){ //if locale file doesn't exists
                param=new String[2];
                locale=new File("locale" + File.separatorChar + "locale.eng.xml");
               
                 new MessageOUTPUT().OUTPUT("er0021",param);
                
            }
          message=ReadMessage(mes,locale,param);
        } catch (Exception er) {
        }
        return message;
    }

    /**
     * Convert String into CP1251. Needed to output cyrilic symbols into console. Used only in Windows OS.
     * @param string not converted string
     * @return string in cp 1251
     */
    public String StringToCp1251(String string) {
        /*Converts string to cp1251 (used only for windows)
         */
        try {
            byte[] tmp1 = string.getBytes("Cp866");

            string = new String(tmp1, "Cp1251");
        } catch (Exception er) {
        }
        return string;
    }

    /**
     * Output message into GUI(if launched) and CUI
     * @param MESSAGE ID of message to output
     */
    public void OUTPUT(String MESSAGE,String[] param) {
        MESSAGE = Message(MESSAGE,param);
        OutputToCUI(MESSAGE); //output to CUI
        OutputToGUI(MESSAGE); //output to GUI
    }

    /**
     * Output message to CUI
     * @param MESSAGE message to output
     */
    public void OutputToCUI(String MESSAGE) {
        //!!!!!!!!!!!!!!!!! ONLY for WINDOWS !!!!!!!!!!!!!!!!!!!!!!!!!!!!//
        if (Parameters.LounchedFromWindows) {
            MESSAGE = StringToCp1251(MESSAGE);
        }
        //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!//
        //CUI output
        System.out.println(MESSAGE);
    }
    /**
     * Output message to GUI
     * @param MESSAGE message to output
     */
    public void OutputToGUI(String MESSAGE) {
        //GUI out
        if (Parameters.GUIAvailable) {
            int k=0;
            boolean find=false;
            do {
           

            } while (!find);
            
        }
    }

    public void PluginOutput(String MESSAGE, String[] param) {
        MESSAGE=PluginMessage(MESSAGE,param);
        OutputToCUI(MESSAGE); //output to CUI
        OutputToGUI(MESSAGE); //output to GUI
    }

    public void OutputToCUIWithoutLogging(String string) {
        throw new UnsupportedOperationException("Not yet implemented");
    }

}
